package com.xiaoxin.experience.service.tree;

import com.xiaoxin.experience.api.tree.model.DirectoryInfo;
import com.xiaoxin.experience.api.tree.model.InstanceInfo;
import com.xiaoxin.experience.api.tree.model.InstanceTree;
import com.xiaoxin.experience.service.tree.common.JsTree;
import com.xiaoxin.experience.service.tree.entity.DirectoryEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author xiaoxin
 */
@Service
public class TreeService
{
    @Resource
    private DirectoryService directoryService;

    @Resource
    private InstanceService instanceService;


    public List<JsTree> getInstanceTree()
    {
        List<DirectoryInfo> directoryList = directoryService.getDirectoryList();
        List<InstanceInfo> instanceList = instanceService.getInstanceList();
        InstanceTree instanceTree = new InstanceTree(directoryList);
        instanceTree.decorateLeaves(instanceList);
        JsTree jsTree = instanceTree.getTreeRoot().buildJsTree(DirectoryInfo::toTreeNode, InstanceInfo::toTreeNode);
        return jsTree.getChildren();
    }

    public boolean saveOrUpdate(DirectoryInfo directoryInfo)
    {
        return directoryService.saveOrUpdate(directoryInfo);
    }

    public boolean saveOrUpdate(InstanceInfo instanceInfo)
    {
        if (instanceInfo == null || instanceInfo.getDirectoryId() == null || instanceInfo.getDirectoryId() < 1)
        {
            return false;
        }
        DirectoryEntity directory = directoryService.getById(instanceInfo.getDirectoryId());
        if (Objects.isNull(directory))
        {
            return false;
        }
        return instanceService.saveOrUpdate(instanceInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDirectory(Integer id)
    {
        boolean deleteDirectory = directoryService.deleteDirectory(id);
        if (deleteDirectory)
        {
            instanceService.deleteByDirectoryId(id);
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean deleteInstance(Integer id)
    {
        return instanceService.deleteInstance(id);
    }
}
